package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;
import com.example.forum.services.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Api(tags = "文章接口")
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IBoardService boardService;
    @Autowired
    private IUserService userService;


    @ApiOperation(("新增文章"))
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("内容") @RequestParam("content") @NonNull String content,
                            @ApiParam("板块id") @RequestParam("boardId") @NonNull Long boardId) {
        //  1. 状态校验
        //  1.1 用户状态校验
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        //  假如拦截器之后，session 不用再校验了
        if(user.getState() == 1) {
            //  用户被禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //  1.2 板块状态校验
        Board board = boardService.selectById(boardId);
        if(board == null || board.getState() == 1 || board.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }

        //  2. 准备数据
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setUserId(user.getId());
        article.setBoardId(boardId);

        //  3. 调用service
        articleService.create(article);
        return AppResult.success();

    }

    @ApiOperation("查询板块文章")
    @GetMapping("/selectlist")
    public AppResult selectList(@ApiParam("板块id") @RequestParam(value = "boardId",required = false) Long boardId) {
        List<Article> articles = null;
        if(boardId == null) {
            articles = articleService.selectList();
        }
        else {
            articles = articleService.selectList(boardId);
        }
        if(articles == null) {
            articles = new ArrayList<>();// 空指针，序列化是"null"，对象为空时才是[]，满足json数组
        }
        return AppResult.success(articles);
    }

    @ApiOperation("查询文章详情")
    @GetMapping("/getdetail")
    public AppResult selectDetailById(HttpServletRequest request,
                            @ApiParam("文章id") @RequestParam("id") @NonNull Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);

        Article article = articleService.selectDetailById(id);
        if(article == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_NOT_EXISTS.getMessage());
        }
        //  判断文章是否属于当前用户
        if(user.getId().equals(article.getUserId())) {
            article.setOwn(true);
        }
        return AppResult.success(article);
    }

    @ApiOperation("修改文章")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("文章id") @RequestParam("id") @NonNull Long id,
                            @ApiParam("新标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("新内容") @RequestParam("content") @NonNull String content) {

        User currentUser = (User) request.getSession().getAttribute(AppConfig.USER_SESSION_KEY);
        User articleUser = userService.selectById(articleService.selectById(id).getUserId());
        //  判断用户是否被禁言
        if(currentUser.getState() == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            throw new ApplicationException(ResultCode.FAILED_USER_BANNED.getMessage());
        }
        //  判断文章归属
        if(!currentUser.getId().equals(articleUser.getId())) {
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            throw new ApplicationException(ResultCode.FAILED_FORBIDDEN.getMessage());
        }
        //  调用mapper
        articleService.modify(id,title,content);
        log.info("更新成功：articleId = " + articleUser.getId());
        return AppResult.success();
    }

    @ApiOperation("更新文章点赞数")
    @PostMapping("/upvote")
    public AppResult upvote(HttpServletRequest request,
                                  @ApiParam("文章id") @RequestParam("id") @NonNull Long articleId) {
        //  1. 校验用户状态
        User user = (User) request.getSession().getAttribute(AppConfig.USER_SESSION_KEY);
        if(user.getState() == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            throw new ApplicationException(ResultCode.FAILED_USER_BANNED.getMessage());
        }
        articleService.upvote(articleId,user.getId());
        return AppResult.success();
    }

    @ApiOperation("删除文章")
    @PostMapping("/delete")
    public AppResult delete(HttpServletRequest request,
                                @ApiParam("文章id") @RequestParam("id") Long id) {
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION_KEY);
        //  1. 校验文章状态
        Article article = articleService.selectById(id);
        if(article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_NOT_EXISTS.getMessage());
        }
        if(article.getState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_BANNED.getMessage());
        }

        //  2. 校验文章归属
        if(!user.getId().equals(article.getUserId())) {
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            throw new ApplicationException(ResultCode.FAILED_FORBIDDEN.getMessage());
        }

        //  3. 调用mapper
        articleService.deleteById(id);
        return AppResult.success();
    }

    @ApiOperation("获取用户所有文章")
    @GetMapping("/getallbyuserid")
    public AppResult getAllByUserId(HttpServletRequest request,
            @ApiParam("用户id") @RequestParam(value = "userId",required = false) Long userId) {

        if(userId == null) {
            //  userId == null 查询的是当前用户的所有文章，否则查询指定用户
            User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION_KEY);
            userId = user.getId();
        }
        //  调用 service
        List<Article> articles = articleService.selectAllByUserId(userId);

        return AppResult.success(articles);
    }


    @ApiOperation("搜索文章")
    @GetMapping("/search")
    public AppResult searchForContent(@ApiParam("关键词") @RequestParam(value = "text",required = false)String text) {
        List<Article> articles = articleService.searchForContent(text);
        return AppResult.success(articles);
    }

    @ApiOperation("获取热门帖子")
    @GetMapping("/gethot")
    public AppResult getHot() {
        List<Object> hotArticles = articleService.getHot();
        return AppResult.success(hotArticles);
    }

}
